{% extends "rules/base.html" %}
{% load static %}
{% load bootstrap3 %}
{% block sidebar %}
    <div class="panel-heading">
        <h2 class="panel-title">{{ rule.sid }}</h2>
    </div>
    <div class="panel-body">
        <ul>
            <li>
                <span class="type">Group rule:</span>
                {{ rule.group }}
            </li>
        </ul>
    </div>
    {% if perms.rules.events_kibana or perms.rules.events_evebox %}
        {% if kibana and kibana_version >= 4 or evebox %}
            <div class="panel-heading">
                <h2 class="panel-title">Events list</h2>
            </div>
            <div class="panel-body">
                <ul>
                    {% if perms.rules.events_kibana %}
                        {% if kibana and kibana_version >= 4 %}
                            <li>
                                {% if kibana_url == '/kibana' %}
                                    <a href="{{ kibana_url }}/../../app/discover#/?_g=(refreshInterval:(display:Off,pause:!f,value:0),time:(from:now-{{ date }},mode:quick,to:now))&_a=(columns:!(_source),filters:!(),index:'logstash-*',interval:auto,query:(query_string:(analyze_wildcard:!t,query:'alert.signature_id:{{ rule.sid }}')),sort:!('@timestamp',desc),vis:(aggs:!((params:(field:_source,orderBy:'2',size:20),schema:segment,type:terms),(id:'2',schema:metric,type:count)),type:histogram))&indexPattern=logstash-*&type=histogram"
                                   target="_blank">
                                {% else %}
                                    <a href="{{ kibana_url }}/app/discover#/?_g=(refreshInterval:(display:Off,pause:!f,value:0),time:(from:now-{{ date }},mode:quick,to:now))&_a=(columns:!(_source),filters:!(),index:'logstash-*',interval:auto,query:(query_string:(analyze_wildcard:!t,query:'alert.signature_id:{{ rule.sid }}')),sort:!('@timestamp',desc),vis:(aggs:!((params:(field:_source,orderBy:'2',size:20),schema:segment,type:terms),(id:'2',schema:metric,type:count)),type:histogram))&indexPattern=logstash-*&type=histogram"
                                   target="_blank">
                                {% endif %}
                                    Kibana
                                </a>
                            </li>
                        {% endif %}
                    {% endif %}
                    {% if perms.rules.events_evebox %}
                        {% if evebox %}
                            <li>
                                <a href="{{ evebox_url }}/#/events?q=alert.signature_id:{{ rule.sid }}"
                                   target="_blank">Evebox</a>
                            </li>
                        {% endif %}
                    {% endif %}
                </ul>
            </div>
        {% endif %}
        {# kibana or evebox #}
    {% endif %}
    {# perms kibana/evebox #}
    {% if perms.rules.ruleset_policy_edit %}
        <div class="panel-heading">
            <h2 class="panel-title">Actions</h2>
        </div>
        <div class="panel-body">
            <ul class="action">
                {% if rule.sid not in rule.READ_ONLY_SIDS %}
                    {% if rules_at_version.0.rulesets|length %}
                        <li>
                            <li>
                                <a href="{% url 'disable_rule' rule.sid %}">Disable rule in ruleset(s)</a>
                            </li>
                            <li>
                                <a href="{% url 'enable_rule' rule.sid %}">Enable rule in ruleset(s)</a>
                            </li>
                            {% if rule.get_transformation_choices|length %}
                                <a href="{% url 'edit_rule' rule.sid %}">Edit rule</a>
                            {% else %}
                                <span class="text-muted">Edit rule</span>
                            {% endif %}
                        </li>
                    {% endif %}
                    {# rule.state #}
                    {% if show_rule_toggle %}
                        <li>
                            <form id="toggle_availability_form_1"
                                  class="form"
                                  action="{% url 'rule_toggle_availability' rule.sid %}"
                                  method="post">
                                {% csrf_token %}
                                <a href="javascript:{}"
                                   onclick="document.getElementById('toggle_availability_form_1').submit(); return false;">
                                    Toggle availability
                                </a>
                            </form>
                        </li>
                    {% endif %}
                {% endif %}
                {% if elasticsearch %}
                    <li>
                        <a href="{% url 'delete_alerts' rule.sid %}">Delete generated alerts</a>
                    </li>
                {% endif %}
            </ul>
        </div>
    {% endif %}
{% endblock sidebar %}
{% block content %}
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-8">
                <h2>{{ rule.msg }}</h2>
            </div>
            {% if references or rule.get_comments %}
                <div class="col-md-4">
                    <div class="panel panel-default" id="reference">
                        {% if references %}
                            <div class="panel-heading">
                                <h2 class="panel-title">References</h2>
                            </div>
                            <div class="panel-body">
                                <ul>
                                    {% for ref in references %}
                                        <li>
                                            {% if ref.url %}
                                                {{ ref.key|capfirst }}:
                                                <a href="{{ ref.url }}" target="_blank">{{ ref.value|truncatechars:80 }}</a>
                                            {% else %}
                                                {{ ref.key }}:  {{ ref.value }}
                                            {% endif %}
                                        </li>
                                    {% endfor %}
                                </ul>
                            </div>
                        {% endif %}
                        {% if rule.get_comments %}
                            <div class="panel-heading">
                                <h2 class="panel-title">Information</h2>
                            </div>
                            <div class="panel-body">
                                Comment
                                <span class="badge">{{ rule.get_comments|length }}</span>
                            </div>
                        {% endif %}
                    </div>
                    <!-- panel -->
                </div>
                <!-- col -->
            {% endif %}
        </div>
        <!-- row -->
        <script>
$(document).ready(function(){
    $('a[data-toggle="tab"]').on('show.bs.tab', function(e) {
        $(this).closest('li').siblings().removeClass('active');
        localStorage.setItem('ruleactiveTab', $(e.target).attr('href'));
        $(this).closest('li').addClass('active');
    });
    var activeTab = localStorage.getItem('ruleactiveTab');
    if(activeTab){
        $('#ruleinfo li').siblings().removeClass('active');
        $('#ruleinfo a[href="' + activeTab + '"]').tab('show');
        $('#ruleinfo a[href="' + activeTab + '"]').closest('li').addClass('active');
    }

    var subactiveTab = localStorage.getItem('rulesubactiveTab');
    if(subactiveTab){
        $('#rule-sub-info li').siblings().removeClass('active');
        $('#rule-sub-info a[href="' + subactiveTab + '"]').tab('show');
        $('#rule-sub-info a[href="' + subactiveTab + '"]').closest('li').addClass('active');
    }
    $("ul.nav-tabs a").click(function (e) {
        e.preventDefault();
        $(this).closest('li').siblings().removeClass('active');
        $(this).closest('li').addClass('active');
        $(this).tab('show');
        localStorage.setItem('rulesubactiveTab', $(e.target).attr('href'));
    });
});
        </script>
        <!-- Nav tabs -->
        <ul class="nav nav-tabs" role="tablist" id="ruleinfo">
            {% if suricata_stats and elasticsearch and perms.rules.events_view %}
                <li role="presentation" class="active">
                    <a href="#stats" aria-controls="stats" role="tab" data-toggle="tab">IP and Time Stats</a>
                </li>
                <li role="presentation">
                    <a href="#metastats"
                       aria-controls="metastats"
                       role="tab"
                       data-toggle="tab">Advanced Data</a>
                </li>
            {% endif %}
            <li role="presentation">
                <a href="#rule_status"
                   aria-controls="rule_status"
                   role="tab"
                   data-toggle="tab">Information</a>
            </li>
            <li role="presentation">
                <a href="#rule_comments"
                   aria-controls="rule_comments"
                   role="tab"
                   data-toggle="tab">History</a>
            </li>
        </ul>
        <div class="tab-content">
            {% if suricata_stats and elasticsearch %}
                <div role="tabpanel" class="tab-pane active" id="stats">
                    <div class="container-fluid">
                        <div class="col-md-4">
                            <div class="container-fluid">
                                <div class="row">
                                    <div class="col-md-12">
                                        <h2 class="title">
                                            Hits by host
                                        </h2>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div id="stats_table">
                                            Fetching data...
                                        </div>
                                    </div>
                                </div>
                                <!-- row -->
                            </div>
                            <!-- container -->
                        </div>
                        <!-- col -->
                        <div class="col-md-4">
                            <div class="container-fluid">
                                <div class="row">
                                    <div class="col-md-12">
                                        <h2 class="title">
                                            Source IP
                                        </h2>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div id="src_ip_table">
                                            Fetching data...
                                        </div>
                                    </div>
                                </div>
                                <!-- row -->
                            </div>
                            <!-- container -->
                        </div>
                        <!-- col -->
                        <div class="col-md-4">
                            <div class="container-fluid">
                                <div class="row">
                                    <div class="col-md-12">
                                        <h2 class="title">
                                            Destination IP
                                        </h2>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-12">
                                        <div id="dest_ip_table">
                                            Fetching data...
                                        </div>
                                    </div>
                                </div>
                                <!-- row -->
                            </div>
                            <!-- container -->
                        </div>
                    </div>
                    <!-- container-fluid -->
                    {% if probes and perms.rules.configuration_view %}
                        <div class="row">
                            <div class="col-md-12">
                                <h2 class="title">
                                    Activity
                                </h2>
                            </div>
                            <!-- col -->
                        </div>
                        <!-- row -->
                        <div class="row">
                            <div class="col-md-12">
                                <div id="timeline">
                                    <p>
                                        Fetching data...
                                    </p>
                                    <svg style="width:100%;height:300px">
                                    </svg>
                                </div>
                                <!-- timeline -->
                            </div>
                            <!-- col -->
                        </div>
                        <!-- row -->
                    {% endif %}
                    {# if probes #}
                </div>
                <!-- tabpanel -->
                <div role="tabpanel" class="tab-pane" id="metastats">
                    <div class="container-fluid">
                        <!--
<div class="col-md-4">
<h2 class="title">Hits by assets</h2>
<div id="stats_table">Fetching data...</div>
</div>
-->
                        <div class="col-md-4">
                            <h2 class="title">
                                Source of attacks
                            </h2>
                            <div id="source_ip_table">
                                Fetching data...
                            </div>
                        </div>
                        <!-- col -->
                        <div class="col-md-4">
                            <h2 class="title">
                                Target of attacks
                            </h2>
                            <div id="target_ip_table">
                                Fetching data...
                            </div>
                        </div>
                    </div>
                    <!-- container-fluid -->
                </div>
                <!-- tabpanel -->
            {% endif %}
            {# suricata_stats and elasticsearch #}
            <div role="tabpanel"
                 class="tab-pane{% if not suricata_stats and not elasticsearch %} active{% endif %}"
                 id="rule_status">
                <div class="container-fluid">
                    <ul class="nav nav-tabs" id="rule-sub-info">
                        {% for rav in rules_at_version %}
                            <li class="{% if forloop.first %}active{% endif %}">
                                <a href="#rule_{{ rav.version }}">
                                    {% if rav.version < 39 %}< v39 {% else %}v{{ rav.version }}{% endif %}
                                </a>
                            </li>
                        {% endfor %}
                    </ul>

                    <div class="tab-content">
                        {% for rav in rules_at_version %}
                            <div class="tab-pane fade {% if forloop.first %}active{% endif %} in" id="rule_{{ rav.version }}">

                                <div class="panel panel-default">
                                    <div class="panel-body">
                                        <div class="col-md-3">
                                            <ul>
                                                <li>
                                                    <span class="type">State in source:</span>
                                                    {% if rav.instance.commented_in_source %}
                                                        Commented
                                                    {% else %}
                                                        Active
                                                    {% endif %}
                                                </li>
                                                <li>
                                                    <span class="type">Revision:</span>
                                                    {{ rav.instance.rev }}
                                                </li>
                                                <li>
                                                    <span class="type">Status:</span>
                                                    {% if rav.instance.state %}
                                                        Active
                                                    {% else %}
                                                        Inactive
                                                    {% endif %}
                                                </li>
                                                <li>
                                                    <span class="type">Imported:</span>
                                                    {{ rav.instance.imported_date }}
                                                </li>
                                                <li>
                                                    <span class="type">Updated:</span>
                                                    {{ rav.instance.updated_date }}
                                                </li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                                <h2 class="title">
                                    Definition
                                </h2>
                                <div class="rule">
                                    {{ rav.content|safe }}
                                </div>
                                {% if rav.rule_transformations %}
                                    <h2 class="title">
                                        Rule transformation(s)
                                    </h2>
                                    {% for ruleset in rav.rulesets %}
                                        {% if ruleset.a_drop or ruleset.a_reject or ruleset.a_filestore or ruleset.a_bypass or ruleset.l_auto or ruleset.l_yes or ruleset.t_auto or ruleset.t_src or ruleset.t_dst %}
                                            <h3 class="title">
                                                {{ ruleset.name }}
                                            </h3>
                                            <div class="rule">
                                                {{ ruleset.content|safe }}
                                            </div>
                                        {% endif %}
                                    {% endfor %}
                                {% endif %}

                                <div class="row">
                                    <div class="col-md-6">
                                        <h2 class="title">
                                            State in source
                                        </h2>
                                        <div class="container-fluid">
                                            <div class="row">
                                                {% if same_real_version %}
                                                <div class="col-md-12 alert alert-warning alert-dismissible">
                                                    Enable/disable in source will be applied on "{{ same_real_version|join:", " }}". They are the same version.
                                                </div>
                                                {% endif %}
                                                <div class="col-md-6">
                                                    <div class="panel panel-default">
                                                        <div class="panel-heading">
                                                            <h2 class="panel-title">
                                                                <a href="{% url 'source' rule.category.source.pk %}">
                                                                    {{ rule.category.source.name }}
                                                                </a>
                                                            </h2>
                                                        </div>
                                                        <div class="panel-body rav-status_{{ rav.version }}" id="{{ rav.pk }}">
                                                            <div class="row">
                                                                <div class="col-md-1" style="margin-right:0.7em;">
                                                                    Status:
                                                                </div>
                                                                <div class="col-md-1">
                                                                    <div class="label space-add {% if rav.instance.state %} label-info{% else %} label-default{% endif %}" style="margin:auto;">
                                                                        <div class="custom-control custom-switch">
                                                                            <form id="toggle_availability_form_{{ rav.instance.pk }}"
                                                                                  class="form"
                                                                                  action="{% url 'rav_toggle_availability' rav.instance.pk %}"
                                                                                  method="post">
                                                                                {% csrf_token %}
                                                                                <a href="javascript:{}"
                                                                                    {% if rule.sid not in rule.READ_ONLY_SIDS %}
                                                                                    onclick="document.getElementById('toggle_availability_form_{{ rav.instance.pk }}').submit(); return false;"
                                                                                    {% endif %}
                                                                                >
                                                                                    <input type="checkbox"
                                                                                           class="custom-control-input"
                                                                                           id="customSwitch1"  {% if rav.instance.state %}checked{% endif %} />
                                                                                    <p class="custom-control-label"
                                                                                           for="customSwitch1" style="padding-top: 3px;">
                                                                                        {% if not rav.instance.state %} Commented {% else %} Active {% endif %}
                                                                                    </p>
                                                                                </a>
                                                                            </form>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>

                                                            <div class="row">
                                                                <div class="col-md-1" style="margin-right:0.7em;">
                                                                    Revision:
                                                                </div>
                                                                <div class="col-md-1">
                                                                    <div class="space-add label label-info" >
                                                                        {{ rav.instance.rev }}
                                                                    </div>
                                                                </div>
                                                            </div>

                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <!-- container-fluid -->
                                    </div>
                                </div>


                                {# rule_transformation #}
                                <div class="row">
                                    <div id="validity_error_{{ rav.version }}" class="col-md-12" style="display:none;">
                                        <h2 class="title">
                                            Rulesets error
                                        </h2>
                                    </div>
                                </div>
                                <div class="row">
                                    <div id="validity_warning_{{ rav.version }}" class="col-md-12" style="display:none;">
                                        <h2 class="title">
                                            Rulesets Warning
                                        </h2>
                                    </div>
                                </div>
                                <div class="row">
                                    <div id="validity_info_{{ rav.version }}" class="col-md-12" style="display:none;">
                                        <h2 class="title">
                                            Rulesets Info
                                        </h2>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <h2 class="title">
                                            State in rulesets
                                        </h2>
                                        <div class="container-fluid">
                                            <div class="row">
                                                {% for ruleset in rav.rulesets %}
                                                    <div class="col-md-6">
                                                        <div class="panel panel-default">
                                                            <div class="panel-heading">
                                                                <h2 class="panel-title">
                                                                    <a href="{% url 'ruleset' ruleset.pk %}">
                                                                        {{ ruleset.name }}
                                                                    </a>
                                                                </h2>
                                                            </div>
                                                            <div class="panel-body ruleset-status_{{ rav.version }}" id="{{ ruleset.pk }}">
                                                                <div class="row">
                                                                    <div class="col-md-1" style="margin-right:0.7em;">
                                                                        Status:
                                                                    </div>
                                                                    <div class="col-md-1">
                                                                        <div class="label space-add {% if ruleset.status == "Enabled" %} label-info{% else %} label-default{% endif %}" style="margin:auto;">
                                                                            {{ ruleset.status }}
                                                                        </div>
                                                                    </div>
                                                                </div>

                                                                <div class="row">
                                                                    <div class="col-md-1" style="margin-right:0.7em;">
                                                                        Validity:
                                                                    </div>
                                                                    <div class="col-md-1">
                                                                        <div class="label label-default" id="validity_{{ rav.version }}" style="margin-right: 1px;">
                                                                            Valid
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                                <div class="row">
                                                                    <div class="col-md-12" style="margin-right:0.7em;">
                                                                        Transformations:
                                                                        {% if ruleset.threshold %}
                                                                            <div class="space-add label label-info" >
                                                                                Threshold
                                                                            </div>
                                                                        {% endif %}
                                                                        {% if ruleset.suppress %}
                                                                            <div class="space-add label label-info" >
                                                                                Suppress
                                                                            </div>
                                                                        {% endif %}
                                                                        {% if ruleset.a_reject %}
                                                                            <div class="space-add label label-info">
                                                                                Reject
                                                                            </div>
                                                                        {% endif %}
                                                                        {% if ruleset.a_drop %}
                                                                            <div class="space-add label label-info">
                                                                                Drop
                                                                            </div>
                                                                        {% endif %}
                                                                        {% if ruleset.a_filestore %}
                                                                            <div class="space-add label label-info">
                                                                                Filestore
                                                                            </div>
                                                                        {% endif %}
                                                                        {% if ruleset.l_auto %}
                                                                            <div class="space-add label label-info">
                                                                                Lateral Auto
                                                                            </div>
                                                                        {% endif %}
                                                                        {% if ruleset.l_yes %}
                                                                            <div class="space-add label label-info">
                                                                                Lateral Yes
                                                                            </div>
                                                                        {% endif %}
                                                                        {% if ruleset.t_auto %}
                                                                            <div class="space-add label label-info">
                                                                                Target Auto
                                                                            </div>
                                                                        {% endif %}
                                                                        {% if ruleset.t_src %}
                                                                            <div class="space-add label label-info">
                                                                                Target Src
                                                                            </div>
                                                                        {% endif %}
                                                                        {% if ruleset.t_dst %}
                                                                            <div class="space-add label label-info">
                                                                                Target Dst
                                                                            </div>
                                                                        {% endif %}
                                                                    </div>
                                                                </div>

                                                            </div>
                                                        </div>
                                                    </div>
                                                {% endfor %}
                                            </div>
                                        </div>
                                        <!-- container-fluid -->
                                    </div>
                                    <!-- col -->
                                    {% if thresholds %}
                                        <div class="col-md-6">
                                            <h2 class="title">
                                                Thresholds
                                            </h2>
                                            {% load render_table from django_tables2 %}
                                            {% render_table thresholds %}
                                        </div>
                                        <!-- col -->
                                    {% endif %}
                                    {% if suppress %}
                                        <div class="col-md-6">
                                            <h2 class="title">
                                                Suppressions
                                            </h2>
                                            {% render_table suppress %}
                                        </div>
                                        <!-- col -->
                                    {% endif %}
                                </div>
                            </div>
                        {% endfor %}
                    </div>


                </div>
            </div>
            <div role="tabpanel" class="tab-pane" id="rule_comments">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-md-10">
                            <h3 class="title">
                                History
                            </h3>
                            <div id="comments">
                                {% if history %}
                                    <div class="list-group list-view-pf list-view-pf-view">
                                        {% for user_action in history %}
                                            {% include "rules/useraction_entry.html" with user_action=user_action %}
                                        {% endfor %}
                                    </div>
                                    <script>
$(document).ready(function () {
    // click the list-view heading then expand a row
    $(".list-group-item-header").click(function(event){
      if(!$(event.target).is("button, a, input, .fa-ellipsis-v")){
        $(this).find(".fa-angle-right").toggleClass("fa-angle-down")
          .end().parent().toggleClass("list-view-pf-expand-active")
            .find(".list-group-item-container").toggleClass("hidden");
      } else {
      }
    })

    // click the close button, hide the expand row and remove the active status
    $(".list-group-item-container .close").on("click", function (){
      $(this).parent().addClass("hidden")
        .parent().removeClass("list-view-pf-expand-active")
          .find(".fa-angle-right").removeClass("fa-angle-down");
    });
});
                                    </script>
                                {% else %}
                                    No comment.
                                {% endif %}
                            </div>
                            {% if perms.rules.ruleset_policy_edit %}
                                <h3 class="title">
                                    Add comment
                                </h3>
                                <form class="form" action="{% url 'comment_rule' rule.sid %}" method="post">
                                    {% csrf_token %}
                                    {% bootstrap_form comment_form %}
                                    {% buttons %}
                                        <button type="submit" class="btn btn-primary">
                                            {% bootstrap_icon "ok" %} Submit
                                        </button>
                                    {% endbuttons %}
                                </form>
                            {% endif %}
                        </div>
                    </div>
                </div>
            </div>
            <!-- tabpanel -->
            <script>
{% if suricata_stats and elasticsearch %}
    {% if probes and perms.rules.configuration_view %}
        $( 'document' ).ready(function () { draw_timeline({{ from_date }}, [{% autoescape off %} {{ probes|join:',' }} {% endautoescape %}], "alert.signature_id:{{ rule.sid }}", 'Hits' ); });
    {% endif %}

function load_stats() {
    $.ajax({
       url: '{% url 'elasticsearch' %}?query=rule&sid={{ rule.sid }}&from_date={{ from_date }}',
          success: function(data) {
             $('#stats_table').empty();
             $('#stats_table').append(data);
          },
	  error: function(data) {
             $('#stats_table').text("Unable to get data.");
             $("#error").text("Unable to get data from Elasticsearch");
             $("#error").parent().toggle();
	  }
    });

}

{% if perms.rules.configuration_view or perms.rules.events_view %}$( 'document' ).ready(load_stats());{% endif %}

function populate_topip_actions(pdiv, field, direction) {
    pdiv.find("td.actions").each(
        function() {
            ip = $(this).parent("tr").children(".host").html();
            content = '<a href="https://www.virustotal.com/gui/ip-address/' + ip + '" target="_blank"><span class="glyphicon glyphicon-question-sign"> </span></a>';
            content = content + '<a href="{% url 'threshold_rule' rule.sid %}?action=threshold&dir=' + direction + '&net=' + ip + '"><span class="glyphicon glyphicon-arrow-down"> </span></a>';
            content = content + ' <a href="{% url 'threshold_rule' rule.sid %}?action=suppress&dir=' + direction + '&net=' + ip + '"><span class="glyphicon glyphicon-remove"> </span></a>';
            $(this).empty();
            $(this).append(content);
	        {% if evebox %}
                $(this).parent("tr").children(".host").css('cursor', 'pointer');
                $(this).parent("tr").children(".host").click( function() {
		        	ip = $(this).text()
                    {% if custom_eve_url %}
                        window.open("{{ custom_eve_url|safe }}" + ip);
                    {% else %}
                        window.open("{{ evebox_url }}/#/events?q=" + field + ":\"" + ip + "\"");
                    {% endif %}
		        });
	        {% endif %}
        }
    );
}

function load_ip_stats() {
    $.ajax({
        url: '{% url 'elasticsearch' %}?query=rule_src&sid={{ rule.sid }}&from_date={{ from_date }}',
        success: function(data) {
           $('#src_ip_table').empty();
           $('#src_ip_table').append(data);
           populate_topip_actions($('#src_ip_table'), 'src_ip', 'src');
        },
	    error: function(data) {
               $('#src_ip_table').text("Unable to get data.");
               $("#error").text("Unable to get data from Elasticsearch");
               $("#error").parent().toggle();
	    }
    });

    $.ajax({
        url: '{% url 'elasticsearch' %}?query=rule_dest&sid={{ rule.sid }}&from_date={{ from_date }}',
        success: function(data) {
           $('#dest_ip_table').empty();
           $('#dest_ip_table').append(data);
           populate_topip_actions($('#dest_ip_table'), 'dest_ip', 'dest');
        },
	    error: function(data) {
            $('#dest_ip_table').text("Unable to get data.");
            $("#error").text("Unable to get data from Elasticsearch");
            $("#error").parent().toggle();
	    }
    });

    $.ajax({
        url: '{% url 'elasticsearch' %}?query=rule_source&sid={{ rule.sid }}&from_date={{ from_date }}',
        success: function(data) {
            $('#source_ip_table').empty();
            $('#source_ip_table').append(data);
            /* FIXME use real method */
            {% if "dest_ip" in rules_at_version.0.content %}
                populate_topip_actions($('#source_ip_table'), 'alert.source.ip', 'src');
            {% else %}
                populate_topip_actions($('#source_ip_table'), 'alert.source.ip', 'dest');
            {% endif %}
        },
	    error: function(data) {
            $('#source_ip_table').text("Unable to get data.");
            $("#error").text("Unable to get data from Elasticsearch");
            $("#error").parent().toggle();
	    }
    });

    $.ajax({
        url: '{% url 'elasticsearch' %}?query=rule_target&sid={{ rule.sid }}&from_date={{ from_date }}',
        success: function(data) {
            $('#target_ip_table').empty();
            $('#target_ip_table').append(data);
            /* FIXME use real method */
            {% if "dest_ip" in rules_at_version.0.content %}
               populate_topip_actions($('#target_ip_table'), 'alert.target.ip', 'dest');
            {% else %}
               populate_topip_actions($('#target_ip_table'), 'alert.target.ip', 'src');
            {% endif %}
        },
	    error: function(data) {
            $('#target_ip_table').text("Unable to get data.");
            $("#error").text("Unable to get data from Elasticsearch");
            $("#error").parent().toggle();
	    }
    });
}

{% if perms.rules.configuration_view %}$( 'document' ).ready(load_ip_stats());{% endif %}
{% endif %} {# suricata_stats and elasticsearch #}
        </script>
    </div>
</div>
<!-- container-fluid -->
<script>
function rule_validity_check() {
    {% for rav in rules_at_version %}
        $("div.ruleset-status_{{ rav.version }}").each(
            function() {
                var ruleset_id = $(this).attr('id');
                var ruleset_name = $(this).parent().find("h2").text();
                var test_url = "{{ rule.get_absolute_url }}test/" + ruleset_id + "?version={{ rav.instance.version }}";
                $.ajax({
                    type:"GET",
                    url: test_url,
                    context: $(this),
                    success: function(data) {
                        if (data['status']) {
                            vlabel = $(this).find("#validity_{{ rav.version }}");
                            vlabel.text('Valid');
                            vlabel.addClass('label-success');
                            vlabel.removeClass('label-default');

                            warning_content = "";
                            if (data['warnings'].length) {
                                for (i = 0; i < data['warnings'].length; i++) {
                                    warning_content += '<li><span class="text-warning"><strong>' + data['warnings'][i]['source'] + '</strong></span>: <span>' + data['warnings'][i]['message'] + '</span></li>';
                                }
                                $("#validity_warning_{{ rav.version }}").append('<h4 class="title">' + ruleset_name + '</h4><div id="warnings"><ul>' + warning_content + '</ul></div>');
                                $("#validity_warning_{{ rav.version }}").show(duration=200);
                            }

                            info_content = "";
                            if (data['info'].length) {
                                for (i = 0; i < data['info'].length; i++) {
                                    info_content += '<li><span class="text-info"><strong>' + data['info'][i]['source'] + '</strong></span>: <span>' + data['info'][i]['message'] + '</span></li>';
                                }
                                $("#validity_info_{{ rav.version }}").append('<h4 class="title">' + ruleset_name + '</h4><div id="info"><ul>' + info_content + '</ul></div>');
                                $("#validity_info_{{ rav.version }}").show(duration=200);
                            }
                        } else {
                            vlabel = $(this).find("#validity_{{ rav.version }}")
                            vlabel.addClass('label-danger');
                            vlabel.text('Invalid');
                            vlabel.removeClass('label-default');
                            error_content = "";
                            if (data['errors'].length) {
                                for (i = 0; i < data['errors'].length; i++) {
                                    error_content += '<li><span class="text-danger"><strong>' + data['errors'][i]['source'] + '</strong></span>: <span>' + data['errors'][i]['message'] + '</span></li>';
                                }
                            }
                            else {
                                error_content = "Unknown error";
                            }
                            $("#validity_error_{{ rav.version }}").append('<h4 class="title">' + ruleset_name + '</h4><div id="errors"><ul>' + error_content + '</ul></div>');
                            $("#validity_error_{{ rav.version }}").show(duration=200);
                        }
                    }
                });
            }
        );
    {% endfor %}
}

$( 'document' ).ready(function() {
    if (window.location.href.indexOf('?no_tests') == -1) {
        rule_validity_check();
    }
});
</script>
{% endblock %}
